/**
 * 上海中赢金融信息服务有限公司
 * Copyright (c) 2016-2026 hmc,Inc.All Rights Reserved.
 */
package com.sys.midware.config.core;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import com.sys.midware.assist.utils.string.StringUtil;
import com.sys.midware.config.exceptions.BConfigFileException;
import com.sys.midware.logger.Logger;
import com.sys.midware.logger.LoggerFactory;
/**
 * 
 * <b>ClassName：</b> ConfigFileUtil <br/>
 * <b>Description：</b> 配置文件加载工具类 <br/>
 * <b>@author：</b> mobing <br/>
 * <b>@date：</b> 2015年10月16日 下午3:45:02 <br/>
 * <b>@version: </b>  <br/>
 */
public class ConfigResource {
	private final static Logger LOG = LoggerFactory.getLogger(ConfigResource.class);
	/**
     * encoding used to read and write xml.
     */
    private static String ENCODING = "UTF-8";
    /**
     * 默认配置文件
     */
    private static final String DEFAULT_CONFIG_PATH = "config/BConfigRoot.xml";
	/**
	 * 根据路径过去资源文件Reader
	 * @param path
	 * @return
	 */
	public static Reader getResourceAsReader(String path) {
		Reader reader = null;
		try {
			reader = new InputStreamReader(getResourceAsStream(path), ENCODING);
		} catch (Exception e) {
			throw new BConfigFileException("read resource error!" +path,e);
		}
		return reader;
	}
	/**
	 * @param path
	 * @return
	 */
	public static InputStream getResourceAsStream(String path) {
		//如果path为空,则走默认的配置文件
		if(StringUtil.isEmpty(path)){
			path= DEFAULT_CONFIG_PATH;
		}
		InputStream inStream = null;// 定义输入流is
		// 从指定文件路径读取，如果没有指定文件路径，则从类路径读取
		try {
			inStream = new FileInputStream(path);
		} catch (FileNotFoundException e) {
			LOG.info("begin to find config from classpath:" + path );
			path = path.startsWith("/") ? path.substring(1) : path;
			ClassLoader classLoader = Thread.currentThread()
					.getContextClassLoader();
			if (classLoader == null) {
				inStream = ClassLoader.getSystemResourceAsStream(path);
			} else {
				inStream = classLoader.getResourceAsStream(path);
			}
			if (inStream == null) {
				throw new BConfigFileException(path + " file not found!");
			}
		}
		return inStream;
	}
	
	

}
